<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content>
    <meta name="keyword" content>
    <link rel="shortcut icon" href="/img/ironman-draw.png">
    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <title>
        
          Task 异步编程测试案例及基础应用说明 - xyzko1 | 博客
        
    </title>

    <link rel="canonical" href="https://xyzko1.github.io/2019/09/01/Task 异步编程测试案例及基础应用说明/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS --> 
    <link rel="stylesheet" href="/css/beantech.min.css">
    
    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css">

    <link rel="stylesheet" href="/css/widget.css">

    <link rel="stylesheet" href="/css/rocket.css">

    <link rel="stylesheet" href="/css/signature.css">

    <link rel="stylesheet" href="/css/toc.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">
	<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        
            background-image: url('Demo.png')
            /*post*/
        
    }
    
    #signature{
        background-image: url('/img/signature/BeanTechSign-white.png');
    }
    
</style>

<header class="intro-header" >
    <!-- Signature -->
    <div id="signature">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                
                    <div class="post-heading">
                        <div class="tags">
                            
                              <a class="tag" href="/tags/#Hexo" title="Hexo">Hexo</a>
                            
                              <a class="tag" href="/tags/#Blog" title="Blog">Blog</a>
                            
                        </div>
                        <h1>Task 异步编程测试案例及基础应用说明</h1>
                        <h2 class="subheading"></h2>
                        <span class="meta">
                            Posted by xyzko1 on
                            2019-09-01
                        </span>
                    </div>
                


                </div>
            </div>
        </div>
    </div>
</header>

	
    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">xyz的博客</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/about/">About</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/tags/">Tags</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/archive/">Archives</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    <!-- Modify by Yu-Hsuan Yen -->

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <blockquote>
<p>created by <a href="https://github.com/xyzko1/xyzko1.github.io" target="_blank" rel="noopener">xyzko1</a><br>
2019年09月01日 19:00:00</p>
</blockquote>
<p>对于多线程，我们经常使用的是Thread。在我们了解Task之前，如果我们要使用多核的功能可能就会自己来开线程，<a href="http://xn--3dsviv32cgvgfrlwka14zcucf60d.net" target="_blank" rel="noopener">然而这种线程模型在.net</a> 4.0之后被一种称为基于“任务的编程模型”所冲击，因为task会比thread具有更小的性能开销，不过大家肯定会有疑惑，任务和线程到底有什么区别呢？<br>
任务和线程的区别：<br>
1、任务是架构在线程之上的，也就是说任务最终还是要抛给线程去执行。<br>
2、任务跟线程不是一对一的关系，比如开10个任务并不是说会开10个线程，这一点任务有点类似线程池，但是任务相比线程池有很小的开销和精确的控制。</p>
<h1><span id="认识task和task的基本使用">认识Task和Task的基本使用</span></h1>
<hr>
<h2><span id="认识task">认识Task</span></h2>
<p>首先来看一下Task的继承结构。Task标识一个异步操作。<br>
<img src="1.png" alt="avatar"><br>
可以看到Task和Thread一样，位于System.Threading命名空间下，这也就是说他们直接有密不可分的联系。下面我们来仔细看一下吧！</p>
<h2><span id="创建task">创建Task</span></h2>
<p>创建Task的方法有两种，一种是直接创建——new一个出来，一种是通过工厂创建。下面来看一下这两种创建方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//第一种创建方式，直接实例化</span></span><br><span class="line"> <span class="keyword">var</span> task1 = <span class="keyword">new</span> Task(<span class="function"><span class="params">()</span> =&gt;</span></span><br><span class="line"> &#123;</span><br><span class="line">    <span class="comment">//TODO you code</span></span><br><span class="line"> &#125;);</span><br></pre></td></tr></table></figure>
<p>这是最简单的创建方法，可以看到其构造函数是一个Action，其构造函数有如下几种，比较常用的是前两种。<br>
<img src="2.png" alt="avatar"></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//第二种创建方式，工厂创建</span></span><br><span class="line"> <span class="keyword">var</span> task2 = Task.Factory.StartNew(<span class="function"><span class="params">()</span> =&gt;</span></span><br><span class="line"> &#123;</span><br><span class="line">    <span class="comment">//TODO you code</span></span><br><span class="line"> &#125;);</span><br></pre></td></tr></table></figure>
<p>这种方式通过静态工厂，创建以个Task并运行。下面我们来建一个控制台项目，演示一下，代码如下：<br>
要添加System.Threading.Tasks命名控件引用。</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;</span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;</span><br><span class="line"><span class="keyword">using</span> System.Linq;</span><br><span class="line"><span class="keyword">using</span> System.Text;</span><br><span class="line"><span class="keyword">using</span> System.Threading.Tasks;</span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> TaskDemo</span><br><span class="line">&#123;</span><br><span class="line">   <span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">   &#123;</span></span><br><span class="line">      <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">         var task1 = <span class="keyword">new</span> <span class="built_in">Task</span>(() =&gt;</span><br><span class="line">         &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"Hello,task"</span>);</span><br><span class="line">         &#125;);</span><br><span class="line">         task1.Start();</span><br><span class="line"></span><br><span class="line">         var task2 = <span class="built_in">Task</span>.Factory.StartNew(() =&gt;</span><br><span class="line">         &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"Hello,task started by task factory"</span>);</span><br><span class="line">         &#125;);</span><br><span class="line"></span><br><span class="line">         <span class="built_in">Console</span>.Read();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里我分别用两种方式创建两个task,并让他们运行。可以看到通过构造函数创建的task,必须手动Start,而通过工厂创建的Task直接就启动了。<br>
下面我们来看一下Task的声明周期，编写如下代码：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">var task1 = <span class="keyword">new</span> <span class="built_in">Task</span>(() =&gt;</span><br><span class="line">   &#123;</span><br><span class="line">      <span class="built_in">Console</span>.WriteLine(<span class="string">"Begin"</span>);</span><br><span class="line">      System.Threading.Thread.Sleep(<span class="number">2000</span>);</span><br><span class="line">      <span class="built_in">Console</span>.WriteLine(<span class="string">"Finish"</span>);</span><br><span class="line">   &#125;);</span><br><span class="line">   <span class="built_in">Console</span>.WriteLine(<span class="string">"Before start:"</span> + task1.Status);</span><br><span class="line">   task1.Start();</span><br><span class="line">   <span class="built_in">Console</span>.WriteLine(<span class="string">"After start:"</span> + task1.Status);</span><br><span class="line">   task1.Wait();</span><br><span class="line">   <span class="built_in">Console</span>.WriteLine(<span class="string">"After Finish:"</span> + task1.Status);</span><br><span class="line"></span><br><span class="line">   <span class="built_in">Console</span>.Read();</span><br></pre></td></tr></table></figure>
<p>task1.Status就是输出task的当前状态，其输出结果如下：<br>
<img src="3.png" alt="avatar"><br>
可以看到调用Start前的状态是Created，然后等待分配线程去执行，到最后执行完成。<br>
从我们可以得出Task的简略生命周期：<br>
Created：表示默认初始化任务，但是“工厂创建的”实例直接跳过。<br>
WaitingToRun: 这种状态表示等待任务调度器分配线程给任务执行。<br>
RanToCompletion：任务执行完毕。</p>
<h1><span id="task的任务控制">Task的任务控制</span></h1>
<hr>
<p>Task最吸引人的地方就是他的任务控制了，你可以很好的控制task的执行顺序，让多个task有序的工作。下面来详细说一下：</p>
<h2><span id="taskwait">Task.Wait</span></h2>
<p>在上个例子中，我们已经使用过了，task1.Wait();就是等待任务执行完成，我们可以看到最后task1的状态变为Completed。</p>
<h2><span id="taskwaitall">Task.WaitAll</span></h2>
<p>看字面意思就知道，就是等待所有的任务都执行完成，下面我们来写一段代码演示一下：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">     var task1 = <span class="keyword">new</span> <span class="built_in">Task</span>(() =&gt;</span><br><span class="line">     &#123;</span><br><span class="line">        <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 1 Begin"</span>);</span><br><span class="line">        System.Threading.Thread.Sleep(<span class="number">2000</span>);</span><br><span class="line">        <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 1 Finish"</span>);</span><br><span class="line">     &#125;);</span><br><span class="line">     var task2 = <span class="keyword">new</span> <span class="built_in">Task</span>(() =&gt;</span><br><span class="line">     &#123;</span><br><span class="line">        <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 2 Begin"</span>);</span><br><span class="line">        System.Threading.Thread.Sleep(<span class="number">3000</span>);</span><br><span class="line">        <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 2 Finish"</span>);</span><br><span class="line">     &#125;);</span><br><span class="line">     </span><br><span class="line">     task1.Start();</span><br><span class="line">     task2.Start();</span><br><span class="line">     <span class="built_in">Task</span>.WaitAll(task1, task2);</span><br><span class="line">     <span class="built_in">Console</span>.WriteLine(<span class="string">"All task finished!"</span>);</span><br><span class="line"></span><br><span class="line">     <span class="built_in">Console</span>.Read();</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>其输出结果如下：<br>
<img src="4.png" alt="avatar"><br>
可以看到，任务一和任务二都完成以后，才输出All task finished！</p>
<h2><span id="taskwaitany">Task.WaitAny</span></h2>
<p>这个用法同Task.WaitAll，就是等待任何一个任务完成就继续向下执行，将上面的代码WaitAll替换为WaitAny，输出结果如下：<br>
<img src="5.png" alt="avatar"></p>
<h2><span id="taskcontinuewith">Task.ContinueWith</span></h2>
<p>就是在第一个Task完成后自动启动下一个Task，实现Task的延续，下面我们来看下他的用法，编写如下代码：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">         var task1 = <span class="keyword">new</span> <span class="built_in">Task</span>(() =&gt;</span><br><span class="line">         &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 1 Begin"</span>);</span><br><span class="line">            System.Threading.Thread.Sleep(<span class="number">2000</span>);</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 1 Finish"</span>);</span><br><span class="line">         &#125;);</span><br><span class="line">         var task2 = <span class="keyword">new</span> <span class="built_in">Task</span>(() =&gt;</span><br><span class="line">         &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 2 Begin"</span>);</span><br><span class="line">            System.Threading.Thread.Sleep(<span class="number">3000</span>);</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"Task 2 Finish"</span>);</span><br><span class="line">         &#125;);</span><br><span class="line"></span><br><span class="line">         </span><br><span class="line">         task1.Start();</span><br><span class="line">         task2.Start();</span><br><span class="line">         var result = task1.ContinueWith&lt;<span class="built_in">string</span>&gt;(task =&gt;</span><br><span class="line">         &#123;</span><br><span class="line">            <span class="built_in">Console</span>.WriteLine(<span class="string">"task1 finished!"</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"This is task result!"</span>;</span><br><span class="line">         &#125;);</span><br><span class="line"></span><br><span class="line">         <span class="built_in">Console</span>.WriteLine(result.Result.ToString());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">         <span class="built_in">Console</span>.Read();</span><br><span class="line">      &#125;</span><br></pre></td></tr></table></figure>
<p>执行结果如下：<br>
<img src="6.png" alt="avatar"><br>
可以看到，task1完成之后，开始执行后面的内容，并且这里我们取得task的返回值。<br>
在每次调用ContinueWith方法时，每次会把上次Task的引用传入进来，以便检测上次Task的状态，比如我们可以使用上次Task的Result属性来获取返回值。我们还可以这么写：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> SendFeedBackTask = Task.Factory.StartNew(<span class="function"><span class="params">()</span> =&gt;</span> &#123; Console.WriteLine(<span class="string">"Get some Data!"</span>); &#125;)</span><br><span class="line">                            .ContinueWith&lt;bool&gt;(<span class="function"><span class="params">s</span> =&gt;</span> &#123; <span class="keyword">return</span> <span class="literal">true</span>; &#125;)</span><br><span class="line">                            .ContinueWith&lt;<span class="built_in">string</span>&gt;(<span class="function"><span class="params">r</span> =&gt;</span> </span><br><span class="line">                              &#123;</span><br><span class="line">                                 <span class="keyword">if</span> (r.Result)</span><br><span class="line">                                 &#123;</span><br><span class="line">                                    <span class="keyword">return</span> <span class="string">"Finished"</span>;</span><br><span class="line">                                 &#125;</span><br><span class="line">                                 <span class="keyword">else</span></span><br><span class="line">                                 &#123;</span><br><span class="line">                                    <span class="keyword">return</span> <span class="string">"Error"</span>;</span><br><span class="line">                                 &#125;</span><br><span class="line">                              &#125;);</span><br><span class="line">         Console.WriteLine(SendFeedBackTask.Result);</span><br></pre></td></tr></table></figure>
<p>首先输出Get some data,然后执行第二个获得返回值true,最后根据判断返回Finished或error。输出结果:<br>
Get some Data!<br>
Finished<br>
其实上面的写法简化一下，可以这样写：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Task.Factory.StartNew&lt;<span class="built_in">string</span>&gt;<span class="function">(<span class="params">(<span class="params"></span>) =&gt; &#123;<span class="keyword">return</span> "One";&#125;</span>).<span class="params">ContinueWith</span>(<span class="params">ss =&gt; &#123; Console.WriteLine(<span class="params">ss.Result</span>);&#125;</span>);</span></span><br></pre></td></tr></table></figure>
<p>输出One，这个可以看明白了吧~<br>
更多ContinueWith用法参见：</p>
<h2><span id="task的取消">Task的取消</span></h2>
<p>前面说了那么多Task的用法，下面来说下Task的取消，比如我们启动了一个task,出现异常或者用户点击取消等等，我们可以取消这个任务。<br>
如何取消一个Task呢，我们通过cancellation的tokens来取消一个Task。在很多Task的Body里面包含循环，我们可以在轮询的时候判断IsCancellationRequested属性是否为True，如果是True的话就return或者抛出异常，抛出异常后面再说，因为还没有说异常处理的东西。<br>
下面在代码中看下如何实现任务的取消，代码如下：</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> tokenSource = new CancellationTokenSource();</span><br><span class="line">         <span class="keyword">var</span> <span class="keyword">token</span> = tokenSource.<span class="keyword">Token</span>;</span><br><span class="line">         <span class="keyword">var</span> task = Task.Factory.StartNew(() =&gt;</span><br><span class="line">         &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">var</span> i = 0; i &lt; 1000; i++)</span><br><span class="line">            &#123;</span><br><span class="line">               System.Threading.Thread.<span class="keyword">Sleep</span>(1000);</span><br><span class="line">               <span class="keyword">if</span> (<span class="keyword">token</span>.IsCancellationRequested)</span><br><span class="line">               &#123;</span><br><span class="line">                  Console.WriteLine(<span class="string">"Abort mission success!"</span>);</span><br><span class="line">                  <span class="keyword">return</span>;</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;, <span class="keyword">token</span>);</span><br><span class="line">         <span class="keyword">token</span>.Register(() =&gt;</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">"Canceled"</span>);</span><br><span class="line">         &#125;);</span><br><span class="line">         Console.WriteLine(<span class="string">"Press enter to cancel task..."</span>);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">         tokenSource.Cancel();</span><br><span class="line">         Console.ReadKey();<span class="comment">//这句忘了加，程序退出了，看不到“Abort mission success!“这个提示</span></span><br></pre></td></tr></table></figure>
<p>这里开启了一个Task,并给token注册了一个方法，输出一条信息，然后执行ReadKey开始等待用户输入，用户点击回车后，执行tokenSource.Cancel方法，取消任务。其输出结果如下：<br>
<img src="7.png" alt="avatar"></p>
<p>好了，今天先说道这里，明天继续讲task，接下来该说说task的异常处理和其他的一些用法，如果喜欢可以关注我，一有更新会马上通知你。<br>
异步编程能充分利用多核计算机，提升程序性能。<br>
请看如下程序：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> object o = <span class="keyword">new</span> object();</span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line"></span><br><span class="line">            var tf = <span class="keyword">new</span> TaskFactory();<span class="comment">//线程池对象</span></span><br><span class="line">            <span class="built_in">Task</span> t1 = tf.StartNew(TaskMenthod, <span class="string">"1"</span>);<span class="comment">//创建并启用线程方法1</span></span><br><span class="line">            <span class="built_in">Task</span> t2 = <span class="built_in">Task</span>.Factory.StartNew(TaskMenthod, <span class="string">"2"</span>);<span class="comment">//创建并启用线程方法2</span></span><br><span class="line">            <span class="built_in">Task</span> t3 = <span class="keyword">new</span> System.Threading.Tasks.<span class="built_in">Task</span>(TaskMenthod, <span class="string">"3"</span>);</span><br><span class="line">            t3.Start();<span class="comment">//创建并启用线程方法3</span></span><br><span class="line">            <span class="built_in">Task</span> t4 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"4"</span>));<span class="comment">//创建并启用线程方法4</span></span><br><span class="line">           </span><br><span class="line">            <span class="comment">//</span></span><br><span class="line">            <span class="built_in">Task</span> t5 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"5"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t6 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"6"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t7 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"7"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t8 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"8"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t9 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"9"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t10 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"10"</span>));</span><br><span class="line">            <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TaskMenthod</span><span class="params">(object title)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            lock (o)<span class="comment">//确保一个线程执行完方法后 其他线程才能进入</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//连续输出四次</span></span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(title.ToString());</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(title.ToString());</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(title.ToString());</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(title.ToString());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>运行结果<br>
<img src="8.png" alt="avatar"><br>
因为Task是异步的，所以输出的结果不是按照1~10的顺序输出的，相信这点大家都能理解。<br>
但是：<br>
我们发现本应在一个方法体内连续输出的四个9却被分成了两部分，为何会这样呢？<br>
这是因为多个Task同时访问TaskMenthod方法，他们之间是无序的，各个Task之间是没有优先级别的，因此会造成上述问题。<br>
如何解决呢？<br>
通过C# LOCK 可以解决，我们对TaskMenthod方法进行加锁即可，代码修正如下：</p>
<h2><span id="task的wait方法">Task的Wait方法</span></h2>
<p><img src="9.png" alt="avatar"><br>
运行代码如下：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">static</span> object o = <span class="keyword">new</span> object();</span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            var tf = <span class="keyword">new</span> TaskFactory();<span class="comment">//</span></span><br><span class="line">            <span class="built_in">Task</span> t1 = tf.StartNew(TaskMenthod, <span class="string">"1"</span>);</span><br><span class="line">            t1.Wait();<span class="comment">//等待线程1 执行完毕后 继续执行</span></span><br><span class="line">            <span class="built_in">Task</span> t2 = <span class="built_in">Task</span>.Factory.StartNew(TaskMenthod, <span class="string">"2"</span>);</span><br><span class="line">            t2.Wait();</span><br><span class="line">            <span class="built_in">Task</span> t3 = <span class="keyword">new</span> System.Threading.Tasks.<span class="built_in">Task</span>(() =&gt; TaskMenthod(<span class="string">"3"</span>));</span><br><span class="line">            t3.Start();</span><br><span class="line">            t3.Wait();</span><br><span class="line">            <span class="built_in">Task</span> t4 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"4"</span>));</span><br><span class="line">            t4.Wait();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//</span></span><br><span class="line">            <span class="built_in">Task</span> t5 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"5"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t6 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"6"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t7 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"7"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t8 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"8"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t9 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"9"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t10 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"10"</span>));</span><br><span class="line">            <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TaskMenthod</span><span class="params">(object title)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            lock (o)<span class="comment">//确保一个线程执行完方法后 其他线程才能进入</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(title);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>以上程序中t1 t2 t3 t4 这四个Task进行了Wait操作，也就是说：其他程序必须等待线程 1 2 3 4 执行完毕后，才能执行，而且线程 1 2 3 4 完全按照代码编写顺序进行输出。<br>
三次执行结果如下：<br>
<img src="10.png" alt="avatar"><br>
<img src="11.png" alt="avatar"><br>
<img src="12.png" alt="avatar"><br>
由上图可知，线程1 2 3 4 的输出牢牢的把控了前四的位置，且是严格按照顺序输出的。</p>
<h2><span id="task的waitall方法">Task的WaitAll方法</span></h2>
<p><img src="13.png" alt="avatar"><br>
将上述代码修改为如下：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">static</span> object o = <span class="keyword">new</span> object();</span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            var tf = <span class="keyword">new</span> TaskFactory();<span class="comment">//线程池对象</span></span><br><span class="line">            <span class="built_in">Task</span> t1 = tf.StartNew(TaskMenthod, <span class="string">"1"</span>);</span><br><span class="line">            <span class="built_in">Task</span> t2 = <span class="built_in">Task</span>.Factory.StartNew(TaskMenthod, <span class="string">"2"</span>);</span><br><span class="line">            <span class="built_in">Task</span> t3 = <span class="keyword">new</span> System.Threading.Tasks.<span class="built_in">Task</span>(() =&gt; TaskMenthod(<span class="string">"3"</span>));</span><br><span class="line">            t3.Start();</span><br><span class="line">            <span class="built_in">Task</span> t4 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"4"</span>));</span><br><span class="line">            <span class="built_in">Task</span>.WaitAll(t1, t2, t3, t4); <span class="comment">//优先执行线程1 2 3 4    线程 1 2 3 4 之间是异步的，也就是说执行顺序是无序的   待线程 1 2 3 4 执行完毕后  才会执行后续的线程</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//</span></span><br><span class="line">            <span class="built_in">Task</span> t5 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"5"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t6 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"6"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t7 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"7"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t8 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"8"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t9 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"9"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t10 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"10"</span>));</span><br><span class="line">            <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TaskMenthod</span><span class="params">(object title)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            lock (o)<span class="comment">//确保一个线程执行完方法后 其他线程才能进入</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(title);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>上面有句注释：Task.WaitAll(t1, t2, t3, t4); //优先执行线程1 2 3 4 线程 1 2 3 4 之间是异步的，也就是说执行顺序是无序的 待线程 1 2 3 4 执行完毕后 才会执行后续的线程<br>
三次执行结果：<br>
<img src="14.png" alt="avatar"><br>
<img src="15.png" alt="avatar"><br>
<img src="16.png" alt="avatar"><br>
由图可知，t1 t2 t3 t4 这四个线程优先执行，但是这四个线程之间的执行是异步的。理解这一点很重要。<br>
继续探讨WaitAll方法<br>
由代码 Task.WaitAll(t1, t2, t3, t4); 可知，必须等待 t1 t2 t3 t4 这四个线程执行完毕后，才会执行下面的操作。、<br>
在此假设名字为t3的线程，我们将 t3.Start(); 去掉，看看会是社么结果：<br>
代码如下：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">  &#123;</span></span><br><span class="line">      <span class="keyword">static</span> object o = <span class="keyword">new</span> object();</span><br><span class="line">      <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          var tf = <span class="keyword">new</span> TaskFactory();<span class="comment">//线程池对象</span></span><br><span class="line">          <span class="built_in">Task</span> t1 = tf.StartNew(TaskMenthod, <span class="string">"1"</span>);</span><br><span class="line">          <span class="built_in">Task</span> t2 = <span class="built_in">Task</span>.Factory.StartNew(TaskMenthod, <span class="string">"2"</span>);</span><br><span class="line">          <span class="built_in">Task</span> t3 = <span class="keyword">new</span> System.Threading.Tasks.<span class="built_in">Task</span>(() =&gt; TaskMenthod(<span class="string">"3"</span>));</span><br><span class="line">          <span class="comment">//t3.Start();  //t3 不执行了</span></span><br><span class="line">          <span class="built_in">Task</span> t4 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"4"</span>));</span><br><span class="line">          <span class="built_in">Task</span>.WaitAll(t1, t2, t3, t4); <span class="comment">//优先执行线程1 2 3 4    线程 1 2 3 4 之间是异步的，也就是说执行顺序是无序的   待线程 1 2 3 4 执行完毕后  才会执行后续的线程</span></span><br><span class="line"></span><br><span class="line">          <span class="comment">//</span></span><br><span class="line">          <span class="built_in">Task</span> t5 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"5"</span>));</span><br><span class="line">          <span class="built_in">Task</span> t6 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"6"</span>));</span><br><span class="line">          <span class="built_in">Task</span> t7 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"7"</span>));</span><br><span class="line">          <span class="built_in">Task</span> t8 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"8"</span>));</span><br><span class="line">          <span class="built_in">Task</span> t9 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"9"</span>));</span><br><span class="line">          <span class="built_in">Task</span> t10 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"10"</span>));</span><br><span class="line">          <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TaskMenthod</span><span class="params">(object title)</span></span></span><br><span class="line"><span class="function">      </span>&#123;</span><br><span class="line">          lock (o)<span class="comment">//确保一个线程执行完方法后 其他线程才能进入</span></span><br><span class="line">          &#123;</span><br><span class="line">              <span class="built_in">Console</span>.WriteLine(title);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>执行结果：<br>
![avatar]17.png)<br>
由此可知：因为 t3 的罢工，导致其他线程一直处于等待状态(得不到执行)，如何解决这个问题呢？<br>
还好，WaitAll方法提供的重载方法中有一个和时间结合的，如下：<br>
<img src="18.png" alt="avatar"><br>
将代码修改如下：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">   &#123;</span></span><br><span class="line">       <span class="keyword">static</span> object o = <span class="keyword">new</span> object();</span><br><span class="line">       <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">       </span>&#123;</span><br><span class="line">           var tf = <span class="keyword">new</span> TaskFactory();<span class="comment">//线程池对象</span></span><br><span class="line">           <span class="built_in">Task</span> t1 = tf.StartNew(TaskMenthod, <span class="string">"1"</span>);</span><br><span class="line">           <span class="built_in">Task</span> t2 = <span class="built_in">Task</span>.Factory.StartNew(TaskMenthod, <span class="string">"2"</span>);</span><br><span class="line">           <span class="built_in">Task</span> t3 = <span class="keyword">new</span> System.Threading.Tasks.<span class="built_in">Task</span>(() =&gt; TaskMenthod(<span class="string">"3"</span>));</span><br><span class="line">           <span class="comment">//t3.Start();  //t3 不执行了  罢工了  咋的吧</span></span><br><span class="line">           <span class="built_in">Task</span> t4 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"4"</span>));</span><br><span class="line"></span><br><span class="line">           <span class="built_in">Task</span>[] tskArray = <span class="keyword">new</span> <span class="built_in">Task</span>[] &#123; t1, t2, t3, t4 &#125;;</span><br><span class="line">           <span class="built_in">Task</span>.WaitAll(tskArray,<span class="number">3000</span>); <span class="comment">//等待三秒后，执行后续线程</span></span><br><span class="line"></span><br><span class="line">           <span class="comment">//</span></span><br><span class="line">           <span class="built_in">Task</span> t5 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"5"</span>));</span><br><span class="line">           <span class="built_in">Task</span> t6 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"6"</span>));</span><br><span class="line">           <span class="built_in">Task</span> t7 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"7"</span>));</span><br><span class="line">           <span class="built_in">Task</span> t8 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"8"</span>));</span><br><span class="line">           <span class="built_in">Task</span> t9 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"9"</span>));</span><br><span class="line">           <span class="built_in">Task</span> t10 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"10"</span>));</span><br><span class="line">           <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TaskMenthod</span><span class="params">(object title)</span></span></span><br><span class="line"><span class="function">       </span>&#123;</span><br><span class="line">           lock (o)<span class="comment">//确保一个线程执行完方法后 其他线程才能进入</span></span><br><span class="line">           &#123;</span><br><span class="line">               <span class="built_in">Console</span>.WriteLine(title);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>这样，在程序等待三秒后，会执行后续操作！</p>
<h2><span id="waitany-方法既是等待任意线程执行完毕后执行后续方法">WaitAny 方法，既是等待任意线程执行完毕后，执行后续方法</span></h2>
<p>将上述程序中的WaitAll 修改成WaitAny 试一下</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Program</span></span></span><br><span class="line"><span class="class">    &#123;</span></span><br><span class="line">        <span class="keyword">static</span> object o = <span class="keyword">new</span> object();</span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span><span class="params">(<span class="built_in">string</span>[] args)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            var tf = <span class="keyword">new</span> TaskFactory();<span class="comment">//线程池对象</span></span><br><span class="line">            <span class="built_in">Task</span> t1 = tf.StartNew(TaskMenthod, <span class="string">"1"</span>);</span><br><span class="line">            <span class="built_in">Task</span> t2 = <span class="built_in">Task</span>.Factory.StartNew(TaskMenthod, <span class="string">"2"</span>);</span><br><span class="line">            <span class="built_in">Task</span> t3 = <span class="keyword">new</span> System.Threading.Tasks.<span class="built_in">Task</span>(() =&gt; TaskMenthod(<span class="string">"3"</span>));</span><br><span class="line">            <span class="comment">//t3.Start();  //t3 不执行了  罢工了  咋的吧</span></span><br><span class="line">            <span class="built_in">Task</span> t4 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"4"</span>));</span><br><span class="line"></span><br><span class="line">            <span class="built_in">Task</span>.WaitAny(t1, t2, t3, t4); <span class="comment">//</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//</span></span><br><span class="line">            <span class="built_in">Task</span> t5 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"5"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t6 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"6"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t7 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"7"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t8 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"8"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t9 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"9"</span>));</span><br><span class="line">            <span class="built_in">Task</span> t10 = <span class="built_in">Task</span>.Run(() =&gt; TaskMenthod(<span class="string">"10"</span>));</span><br><span class="line">            <span class="built_in">Console</span>.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TaskMenthod</span><span class="params">(object title)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            lock (o)<span class="comment">//确保一个线程执行完方法后 其他线程才能进入</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="built_in">Console</span>.WriteLine(title);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<hr>
<!-- Place this tag in your head or just before your close body tag. -->
<script async defer src="https://buttons.github.io/buttons.js"></script>
<!-- Place this tag where you want the button to render. -->
<p>Please <a class="github-button" href="https://github.com/xyzko1/myblog" data-icon="octicon-star" aria-label="Star xyzko1/myblog on GitHub" target="_blank" rel="noopener">Star</a> this Project if you like it! <a class="github-button" href="https://github.com/xyzko1" aria-label="Follow @xyzko1 on GitHub" target="_blank" rel="noopener">Follow</a> would also be appreciated!<br>
Peace!</p>

                

                <hr>
                <!-- Pager -->
                <ul class="pager">
                    
                    
                        <li class="next">
                            <a href="/2019/08/13/常见的Web实时消息交互方式和SignalR/" data-toggle="tooltip" data-placement="top" title="常见的Web实时消息交互方式和SignalR">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                <!-- duoshuo Share start -->
                
                <!-- 多说 Share end-->

                <!-- 多说评论框 start -->
                
                <!-- 多说评论框 end -->

                <!-- disqus comment start -->
                
                    <div class="comment">
                        <div id="disqus_thread" class="disqus-thread"></div>
                    </div>
                
                <!-- disqus comment end -->
            </div>
            
            <!-- Tabe of Content -->
            <!-- Table of Contents -->

    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">Contents</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">认识Task和Task的基本使用</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.1.</span> <span class="toc-nav-text">认识Task</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">1.2.</span> <span class="toc-nav-text">创建Task</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">Task的任务控制</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.1.</span> <span class="toc-nav-text">Task.Wait</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.2.</span> <span class="toc-nav-text">Task.WaitAll</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.3.</span> <span class="toc-nav-text">Task.WaitAny</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.4.</span> <span class="toc-nav-text">Task.ContinueWith</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.5.</span> <span class="toc-nav-text">Task的取消</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.6.</span> <span class="toc-nav-text">Task的Wait方法</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.7.</span> <span class="toc-nav-text">Task的WaitAll方法</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#null"><span class="toc-nav-number">2.8.</span> <span class="toc-nav-text">WaitAny 方法，既是等待任意线程执行完毕后，执行后续方法</span></a></li></ol></li></ol>
        
        </div>
      </aside>
    

                
            <!-- Sidebar Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/tags/#Hexo" title="Hexo">Hexo</a>
                        
                          <a class="tag" href="/tags/#Blog" title="Blog">Blog</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="http://beantech.org" target="_blank">Bean Tech</a></li>
                    
                        <li><a href="http://blog.kaijun.rocks" target="_blank">Kaijun&#39;s Blog</a></li>
                    
                        <li><a href="http://huangxuan.me" target="_blank">Hux Blog</a></li>
                    
                        <li><a href="#" target="_blank">It Helps SEO</a></li>
                    
                </ul>
                
            </div>
        </div>
    </div>
</article>




<!-- disqus embedded js code start (one page only need to embed once) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "your-disqus-ID";
    var disqus_identifier = "https://xyzko1.github.io/2019/09/01/Task 异步编程测试案例及基础应用说明/";
    var disqus_url = "https://xyzko1.github.io/2019/09/01/Task 异步编程测试案例及基础应用说明/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus embedded js code start end -->




<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'hover',
          placement: 'left',
          icon: 'ℬ'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>



    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                

                

                
                    <li>
                        <a target="_blank" href="https://www.facebook.com/xyzko1">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                
                    <li>
                        <a target="_blank"  href="https://github.com/xyzko1">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                
                    <li>
                        <a target="_blank"  href="https://www.linkedin.com/in/xyzko1">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; xyzko1 2021 
                    <br>
                    Theme by <a href="http://huangxuan.me">Hux</a> 
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span> 
                    re-Ported by <a href="http://beantech.org">BeanTech</a> | 
                    <iframe
                        style="margin-left: 2px; margin-bottom:-5px;"
                        frameborder="0" scrolling="0" width="91px" height="20px"
                        src="https://ghbtns.com/github-btn.html?user=YenYuHsuan&repo=hexo-theme-beantech&type=star&count=true" >
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("https://xyzko1.github.io/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->


<script>
    // dynamic User by Hux
    var _gaId = 'UA-XXXXXXXX-X';
    var _gaDomain = 'yoursite';

    // Originial
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', _gaId, _gaDomain);
    ga('send', 'pageview');
</script>




<!-- Baidu Tongji -->






	<a id="rocket" href="#top" class=""></a>
	<script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
    <script type="text/javascript" src="/js/toc.js?v=1.0.0" async=""></script>
<!-- Image to hack wechat -->
<img src="https://xyzko1.github.io/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
